<?php
declare (strict_types=1);

namespace app\common\event\listeners\notify;

use app\admin\logic\system\Config as SystemConfig;
use app\admin\logic\system\notify\NotifyNode;
use app\admin\logic\user\Account as AdminUser;
use app\admin\model\system\Message as SystemMessage;
use app\user\logic\user\Account as User;
use app\user\model\user\SystemNotify;
use eduline\sms\Client;

/**
 * 消息通知
 */
class Notify
{
    public function handle($data)
    {
        // system_notify:系统通知前台、system_message:系统通知后台、notify_message:前台用户私信
        $type = $data['type'] ?? '';
        $key  = $data['key'] ?? '';
        // Db::name('test')->save(['msg'=>"测试课程购买短信通知type:".$type."，key:".$key]);
        $node = $this->getNotifyNodeByKey($key);
        if ($node->isEmpty()) return;
        // Db::name('test')->save(['msg'=>json_encode($data['var'])]);
        $openInfo = $node->open_info;
        if (!empty($openInfo)) {

            switch ($type) {
                case 'system_message':
                    $this->handleSystemMessage($data);
                    break;

                case 'system_notify':
                    $this->handleSystemNotify($data, $node);
                    break;

                case 'notify_message':
                    $this->handleNotifyMessage($data);
                    break;
            }
        }
    }

    public function handleSystemMessage($data)
    {
        $node = $this->getNotifyNodeByKey($data['key']);
        $var  = $data['var'] ?? [];
        $var  = is_array($var) ? $var : [];
        $user = $data['user'] ?? 0;

        if (!$user) return;

        $openInfo = $node->open_info ?: [];
        if (!count($openInfo)) return;

        foreach ($openInfo as $way) switch ($way) {
            case 'system_notify':
                $content = $node->content;
                if (count($var)) {
                    $content = $this->handleSysVarInParam($var, $content);
                }

                SystemMessage::create([
                    'admin_user_id' => $user,
                    'title'         => $node->title,
                    'content'       => $content,
                    'message_type'  => $data['key'],
                ]);
                break;

            case 'sms':
                /** @var AdminUser $user */
                $userLogic = app(AdminUser::class);
                $this->sendSMS($userLogic, $user, $data, $var, $node);
                break;

            default:
                # code...
                break;
        }

    }

    public function handleSystemNotify($data, $node)
    {
        $var  = $data['var'] ?? [];
        $var  = is_array($var) ? $var : [];
        $user = $data['user'] ?? 0;

        if (!$user) return;

        $openInfo = $node->open_info ?: [];
        if (!count($openInfo)) return;

        foreach ($openInfo as $way) {
            switch ($way) {
                case 'system_notify':
                    $content = $node->content;
                    if (count($var)) {
                        $content = $this->handleSysVarInParam($var, $content);
                    }

                    SystemNotify::create([
                        'user_id' => $user,
                        'title'   => $node->title,
                        'content' => $content,
                    ]);
                    break;

                case 'sms':
                    /** @var User $user */
                    $userLogic = app(User::class);
                    $this->sendSMS($userLogic, $user, $data, $var, $node);
                    break;

                default:
                    # code...
                    break;
            }
        }
    }

    public function handleNotifyMessage($data)
    {
        # code...
    }

    public function sendSMS($userLogic, $user, $data, $var, $node)
    {
        $phone  = $userLogic->getUserPhone($user);
        $mhm_id = $userLogic->getUsermhmId($user);
        $sms    = SystemConfig::get('system.package.sms', [], $mhm_id);
        // Db::name('test')->save(['msg'=>"has_sms:".$node->has_sms."，phone:".$phone."，temp:".$node->sms_template_code."，sms:".json_encode($sms)]);
        switch ($data['key']) {
            case 'register':
                if (isset($sms['provider']) && $sms['provider'] == 'tencent') $var = [];
                break;

            case 'encashment_success':
            case 'teacher_auth_pass':
                unset($var['reason']);
                break;

        }
        if ($node->has_sms && $phone && $node->sms_template_code && $sms) {
            Client::send($phone . '', $var, ['TemplateCode' => $node->sms_template_code]);
        }
    }

    public function getNotifyNodeByKey($key)
    {
        return app(NotifyNode::class)->getNotifyNodeDataByKey($key);
    }

    public function handleSysVarInParam($var, $content)
    {
        foreach ($var as $k => $v) {
            if (false !== stristr($content, "{{" . $k . "}}")) {
                $content = str_replace("{{" . $k . "}}", $v, $content);
            }
        }

        return $content;
    }

}
